/**
 * 
 */
package server.internal;

import static commons.Preconditions.checkNotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import server.StorageUnitID;
import server.StorageUnitResolver;

import commons.exception.AlreadyUsedNameException;
import commons.exception.NotFoundNameException;

/**
 * @author armstrong
 * 
 */
public class Namespace implements StorageUnitResolver {

	private final Map<String, StorageUnitID>	namesMap;

	public Namespace(final Map<String, StorageUnitID> namesMap) {

		checkNotNull("namesMap cannot be null", namesMap);

		this.namesMap = namesMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#delete(java.lang.String)
	 */
	@Override
	public void delete(final String name) throws NotFoundNameException {

		checkNotNull("name cannot be null.", name);

		if (namesMap.remove(name) == null) {

			throw new NotFoundNameException("name not found: " + name);
		}

		namesMap.remove(name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#exist(java.lang.String)
	 */
	@Override
	public boolean exist(final String name) {

		checkNotNull("name cannot be null.", name);

		return namesMap.containsKey(name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#list()
	 */
	@Override
	public List<String> list() {
		return new ArrayList<String>(namesMap.keySet());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#create(java.lang.String)
	 */
	@Override
	public void map(final String name, final StorageUnitID object)
			throws AlreadyUsedNameException {

		checkNotNull("name cannot be null.", name);
		checkNotNull("object cannot be null.", object);

		if (!namesMap.containsKey(name)) {

			namesMap.put(name, object);
		} else {

			throw new AlreadyUsedNameException("already used name:" + name);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#resolve(java.lang.String)
	 */
	@Override
	public StorageUnitID resolve(final String name)
			throws NotFoundNameException {

		checkNotNull("name cannot be null.", name);

		if (!namesMap.containsKey(name)) {

			throw new NotFoundNameException("not found name:" + name);
		}

		return namesMap.get(name);
	}
}
